import { ref } from 'vue'
import { defineStore } from 'pinia'  
import router, { filterAsyncRoutes } from '@/router'
import { setItem, getItem, removeAllItem } from '@/utils/storage'  
import { loginService,getUserInfoApi } from "@/apis/system/admin"
import { useTabsStore } from './multipleTabs'
import { PageEnum } from '@/enums/pageEnum'
import { clearAuthInfo } from '@/utils/auth'

export const useUserStore = defineStore('users', () => {  
    const token = ref(getItem('token') || '')
    const userInfo =  ref({})
    const routes = ref([])
    const perms = ref([]) 
    const login = async (user) => { 
      const { user_name, password } = user
      return new Promise((resolve, reject) => {
        loginService({
          username:user_name,
          password
        }).then(data => { 
           token.value = data.token
           setItem('token', data.token)  
           setItem('userId', data.userinfo.id)       
           resolve()
          }).catch(err => {
            reject(err)
          })
      })
    } 
    const resetState = () => {
      token.value = ''
      userInfo.value = {}
      perms.value = []
    } 

     const loginOut = async () => {  
        token.value = ''
        await router.push(PageEnum.LOGIN)
        clearAuthInfo()
     }

     const getUserInfo = async () => {
       await getUserInfoApi({
        id:getItem('userId')
       }).then(data=>{
         userInfo.value = data.account
         routes.value = filterAsyncRoutes(data.menus)
         perms.value = data.permissions
       })  
    }
      
  return { login,token,userInfo,loginOut,getUserInfo,routes,perms,resetState }
})
